package com.wfcm.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.wfcm.entity.*;
import com.wfcm.service.*;
import com.wfcm.utils.ISsoLoginHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wfcm.utils.DateUtil;
import com.wfcm.utils.R;
import com.wfcm.utils.WebUtils;

@Controller
@RequestMapping("iap")
public class IapController {
    @Autowired
    private WfMemberGoldLogService memberGoldLogService;
    @Autowired
    private WfMemberNewGoldLogService memberNewGoldLogService;
    @Autowired
    private WfMemberGiveCoinLogService memberGiveCoinLogService;
    @Autowired
    private WfMemberRechargeOrderService memberRechargeOrderService;
    @Autowired
    private WfIospayErrorService iospayErrorService;
    private static ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();

    //购买凭证验证地址  
    private static final String certificateUrl = "https://buy.itunes.apple.com/verifyReceipt";

    //测试的购买凭证验证地址   
    private static final String certificateUrlTest = "https://sandbox.itunes.apple.com/verifyReceipt";

    /**
     * 重写X509TrustManager
     */
    private static TrustManager myX509TrustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }
    };


    /**
     * 接收iOS端发过来的购买凭证
     *
     * @param
     */
    @RequestMapping("/newSetIapCertificate")
    @ResponseBody
    public R newSetIapCertificate(HttpServletRequest req) {
        final Integer uid = ISsoLoginHelper.confirm(req);
        String certificateCode = req.getParameter("certificateCode");
        String productId = req.getParameter("productId");
        String transactionCode = req.getParameter("transactionCode");//app生成充值订单号，验证是否已充值
        String transactionIdentifier = req.getParameter("transactionIdentifier");

        final String rebate = req.getParameter("rebate");//赠送金额
        String type = req.getParameter("type");//1、正式  2、测试
        String url = type.equals("1") ? certificateUrl : certificateUrlTest;
        //url = certificateUrl;  //正式
        R rr = getMoney(productId);//获取金额
        String money = (String)rr.get("money");
        String t = (String)rr.get("type");//1充值比例1:1   0充值比例0.7
        //先判断是否充值过
        if (ISsoLoginHelper.confirmPay(uid, transactionCode)) {//验证订单是否已经充值
            return R.ok().put("pay",0);//返回pay=0,订单已充值
        }
        //首次保存记录
        this.saveError(certificateCode,money,rebate,"110",type,uid,"首次保存");
        if (StringUtils.isNotEmpty(certificateCode)) {
            String code = "";
            String environment = "";
            String transaction_id = "";
            String r = sendHttpsCoon(url, certificateCode);
            JSONObject params = JSONObject.parseObject(r);

            final String orderNum = DateUtil.getRechargeOrderNum();//根据当前时间生成订单号，yyMMddHHmmssSSS + 0~1000000随机数
            if (params != null) {
                code = String.valueOf(params.get("status"));
                this.saveError(certificateCode,money,rebate,code,type,uid,params.toString());//第二次保存记录
                if ("0".equals(code)) {//成功
                    ISsoLoginHelper.savePay(uid, transactionCode, money);//redis保存充值记录
                    return paramRecharge(params,rebate,orderNum,uid,money,transactionIdentifier,type);
                } else if("21007".equals(code)){//如果是测试环境，则更改为测试网址
                    r = sendHttpsCoon(certificateUrlTest, certificateCode);
                    params = JSONObject.parseObject(r);
                    System.out.println("*****************" + params);
                    if (params != null) {
                        code = String.valueOf(params.get("status"));
                        if ("0".equals(code)) {//成功
                            ISsoLoginHelper.savePay(uid, transactionCode, money);//redis保存充值记录
                            return paramRecharge(params,rebate,orderNum,uid,money,transactionIdentifier,type);
                        }else{
                            return R.error();
                        }
                    } else {
                        this.saveError(certificateCode,money,rebate,"111",type,uid,"第三次保存");//第三次保存记录
                        return timerRun(url,certificateCode,environment,money,transaction_id,uid,rebate,orderNum,transactionCode,type);
                    }
                }else {//失败,异步循环调用
                   return  timerRun(url,certificateCode,environment,money,transaction_id,uid,rebate,orderNum,transactionCode,type);
                }
            }else {
                this.saveError(certificateCode,money,rebate,"111",type,uid,"第二次保存param为空");//第二次保存记录
                return timerRun(url,certificateCode,environment,money,transaction_id,uid,rebate,orderNum,transactionCode,type);
            }
        } else {
            String orderNum = DateUtil.getRechargeOrderNum();//根据当前时间生成订单号，yyMMddHHmmssSSS + 0~1000000随机数
            ISsoLoginHelper.savePay(uid, transactionCode, money);//redis保存充值记录
            //保存充值记录
            saveRecharge(rebate, orderNum, uid, money, type.equals("1")?"production":"iosAppSandbox", StringUtils.isNotEmpty(transactionIdentifier)?transactionIdentifier:"no_certificateCode",type);
            return R.ok().put("pay",1);//充值成功返1
        }
    }

    private void saveRecharge(String rebate,String orderNum,Integer uid, String money,String environment,String transaction_id,String type) {
        //若支付成功，保存金币充值数据，充值记录数据，添加铜钱赠送数据，奖励邀请人
        //铜钱赠送
        if(!"0".equals(rebate)){
            WfMemberGiveCoinLogEntity memberGiveCoinLog = new WfMemberGiveCoinLogEntity();//充值赠送新铜钱
            memberGiveCoinLog.setCoinvalue(new BigDecimal(rebate));//赠送铜钱
            memberGiveCoinLog.setCreatetime(new Date());
            memberGiveCoinLog.setOrdercode("ios-"+orderNum);
            memberGiveCoinLog.setStatus(2);//1，进行中； 2，完成
            memberGiveCoinLog.setType(1);//1，赚；2，花
            memberGiveCoinLog.setUserid(uid);
            memberGiveCoinLog.setSource(2);//赠送
            memberGiveCoinLogService.save(memberGiveCoinLog);
        }


        if("0".equals(type)) {
            //金币充值
            WfMemberGoldLogEntity memberGoldLog = new WfMemberGoldLogEntity();
            memberGoldLog.setCreatetime(new Date());
            memberGoldLog.setGoldvalue(new BigDecimal(money));//充值的金币
            memberGoldLog.setOrderNo("ios-" + orderNum);
            memberGoldLog.setStatus(2);//1，进行中； 2，完成
            memberGoldLog.setType(1);//1，赚；2，花
            memberGoldLog.setUserid(uid);
            memberGoldLog.setUsersource("---iosApp" + environment);
            memberGoldLogService.save(memberGoldLog);
        }else if("1".equals(type)) {
            //金币充值
            WfMemberNewGoldLogEntity memberNewGoldLog = new WfMemberNewGoldLogEntity();
            memberNewGoldLog.setCreatetime(new Date());
            memberNewGoldLog.setGoldvalue(new BigDecimal(money));//充值的金币
            memberNewGoldLog.setOrderNo("ios-" + orderNum);
            memberNewGoldLog.setStatus(2);//1，进行中； 2，完成
            memberNewGoldLog.setType(1);//1，赚；2，花
            memberNewGoldLog.setUserid(uid);
            memberNewGoldLog.setUsersource("---iosApp" + environment);
            memberNewGoldLogService.save(memberNewGoldLog);
        }

        //充值订单记录数据
        WfMemberRechargeOrderEntity memberRechargeOrder = new WfMemberRechargeOrderEntity();
        memberRechargeOrder.setUserid(uid);
        memberRechargeOrder.setRechargeMoney(new BigDecimal(money));
        memberRechargeOrder.setOrderNo("ios-"+orderNum);
        memberRechargeOrder.setRebate(new BigDecimal(rebate));
        memberRechargeOrder.setTransactionId("ios-"+transaction_id);
        memberRechargeOrder.setOrderPaytime(new Date());
        memberRechargeOrder.setPayType(3);//支付类型（1微信2支付宝，3苹果）
        memberRechargeOrder.setOrderStatus(3);//订单类型（1生成订单2支付中3支付成功）
        memberRechargeOrder.setOrderTime(new Date());
        memberRechargeOrder.setUpdatetime(new Date());
        if("1".equals(type)){
            memberRechargeOrder.setUsersource("---iosApp"+environment+"--1:1");
        } else{
            memberRechargeOrder.setUsersource("---iosApp"+environment+"--1:0.7");
        }
        memberRechargeOrderService.save(memberRechargeOrder);

    }

    /**
     * 保存iosApp请求记录
     * @param
     * @param
     * @return
     */
    private R timerRun(String url,String certificateCode, String environment, String money,String transaction_id,Integer uid, String rebate, String orderNum,String transactionCode,String type){
        final String url1 = url;
        final String certificateCode1 = certificateCode;
        final String environment1 = environment;
        final String transaction_id1 = transaction_id;
        final String money1 = money;//充值金额
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                if (map.get(certificateCode1) != null) {
                    map.put(certificateCode1, map.get(certificateCode1) + 1);
                } else {
                    map.put(certificateCode1, 1);
                }
                if (map.get(certificateCode1) >= 60) {
                    map.remove(certificateCode1);
                    timer.cancel();
                }
                String r1 = sendHttpsCoon(url1, certificateCode1);
                if (JSONObject.parseObject(r1).getString("status").equals("0")) {
                    ISsoLoginHelper.savePay(uid, transactionCode, money);//redis保存充值记录
                    saveRecharge(rebate, orderNum, uid, money1, environment1, transaction_id1,type);//进行充值
                    map.remove(certificateCode1);
                    timer.cancel();
                }
                //System.out.println("设定指定任务task在指定延迟delay后执行");
            }
        }, 1000, 10000);

        return R.error("68");
    }

    /**
     * 充值成功，根据param充值
     * @param
     * @param
     * @return
     */
    private R paramRecharge(JSONObject  params,String rebate,String orderNum, Integer uid, String money,String transactionIdentifier,String type){
        String code = "";
        String environment = "";
        String transaction_id = "";
        environment = String.valueOf(params.get("environment"));
        String r_receipt = params.getString("receipt");
        JSONObject returnJson = JSONObject.parseObject(r_receipt);
        JSONArray jsonArray = (JSONArray) returnJson.get("in_app");// 订单列表
        JSONObject targetOrder = null;
        String product_id = null;
        for (int i = 0; i < jsonArray.size(); i++) {
            targetOrder = jsonArray.getJSONObject(i);//获取订单信息对象
            product_id = targetOrder.getString("product_id");//获取产品信息
            transaction_id = targetOrder.getString("transaction_id");// transaction_id交易号
            if (transaction_id.equals(transactionIdentifier)) {
                R r = getMoney(product_id);
                money = (String)r.get("money");
                type = (String)r.get("type");//1充值比例1:1   0充值比例0.7
                //进行充值
                saveRecharge(rebate, orderNum, uid, money, environment, transaction_id,type);
            } else {
                continue;
            }
        }
        return R.ok().put("pay", 1);//充值成功返1
    }

        /**
         * 保存iosApp请求记录
         * @param
         * @param
         * @return
         */
        private void saveError(String certificateCode, String money,String rebate,String resultCode,String type, Integer uid,String remark){
            WfIospayErrorEntity payError = new WfIospayErrorEntity();
            payError.setCertificatecode(certificateCode == null?"no_certificateCode":certificateCode);
            payError.setMoney(money);
            payError.setRebate(rebate);
            payError.setResultcode(resultCode);
            payError.setType(type);
            payError.setUid(String.valueOf(uid));
            payError.setUpdatetime(new Date());
            payError.setRemark(remark);
            iospayErrorService.save(payError);
        }


        /**
         * productId获取对应产品金额
         * @param
         * @param
         * @return
         */
        private R getMoney(String productId){
            R r = new R();
            String money = null;//充值金额
            String type = "1"; //1充值比例1:1   0充值比例0.7
            if(productId.equals("com.BeijingICanIShowEducation.fourc")){
                money = "4"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.fourb")){
                money = "12"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.thirty")){
                money = "30";  type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.fouara")){
                money = "35"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.SixtyTwo")){
                money = "62"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.SixtyTwThree")){
                money = "132"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.Twohundredandninetyeight")){
                money = "298"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.SixtyTw")){
                money = "412"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.SixHundredAndNinetyNine")){
                money = "699"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.Ninehundredandninetyeight")){
                money = "998"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.OneThousandoneHundred")){
                money = "1189"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.OneThousandThreeHundred")){
                money = "1399"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.OneThousandThreeHundred")){
                money = "1399"; type = "0";
            }else if(productId.equals("com.BeijingICanIShowEducation.levelZ")){
                money = "18";
            }else if(productId.equals("com.BeijingICanIShowEducation.levelY")){
                money = "68";
            }else if(productId.equals("com.BeijingICanIShowEducation.levelX")){
                money = "88";
            }else if(productId.equals("com.BeijingICanIShowEducation.levelW")){
                money = "188";
            }else if(productId.equals("com.BeijingICanIShowEducation.levelV")){
                money = "288";
            }else if(productId.equals("com.BeijingICanIShowEducation.levelU")){
                money = "388";
            }
            r.put("money",money);
            r.put("type",type);
            return r;
        }

        /**
         * 发送请求
         * @param url
         * @param
         * @return
         */
        private String sendHttpsCoon(String url, String code){
            if(url.isEmpty()){
                return null;
            }
            try {
                //设置SSLContext
                SSLContext ssl = SSLContext.getInstance("SSL");
                ssl.init(null, new TrustManager[]{myX509TrustManager}, null);

                //打开连接
                HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
                //设置套接工厂
                conn.setSSLSocketFactory(ssl.getSocketFactory());
                //加入数据
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-type","application/json");

                JSONObject obj = new JSONObject();
                obj.put("receipt-data", code);

                BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
                buffOutStr.write(obj.toString().getBytes());
                buffOutStr.flush();
                buffOutStr.close();

                //获取输入流
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String line = null;
                StringBuffer sb = new StringBuffer();
                while((line = reader.readLine())!= null){
                    sb.append(line);
                }
                return sb.toString();

            } catch (Exception e) {
                return null;
            }
        }

        /**
         * 向指定 URL 发送POST方法的请求
         *
         * @param url
         *            发送请求的 URL
         * @param param
         *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
         * @return 所代表远程资源的响应结果
         */
        public static  synchronized String sendPost(String url, String param) {


            StringBuilder sb = new StringBuilder();
            PrintWriter out = null;
            BufferedReader in = null;
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                //JSONObject obj = new JSONObject(param);
                out.print(JSON.parseObject(param));
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                sb = new StringBuilder();

                while ((line = in.readLine()) != null)
                {
                    sb.append(line);
                }
            } catch (Exception e) {
                // System.out.println("发送 POST 请求出现异常！"+e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            return sb.toString();
        }


        /**
         * 接收iOS端发过来的购买凭证
         *
         * @param
         */
        @RequestMapping("/setIapCertificate")
        @ResponseBody
        public R setIapCertificate(HttpServletRequest req) {
            final Integer uid = ISsoLoginHelper.confirm(req);
            String certificateCode = req.getParameter("certificateCode");
            String money = req.getParameter("money");//充值金额
            final String rebate = req.getParameter("rebate");//赠送金额
            String type = req.getParameter("type");//1、正式  2、测试
            String url = null;
            url = type.equals("1") ? certificateUrl : certificateUrlTest;
            //url = certificateUrl;  //正式
            WfAppVersionEntity a = new WfAppVersionEntity();
            if ("88".equals(money)) {
                money = "62";
            } else if ("188".equals(money)) {
                money = "132";
            } else if ("588".equals(money)) {
                money = "412";
            } else if ("998".equals(money)) {
                money = "699";
            } else if ("1598".equals(money)) {
                money = "1189";
            } else if ("1998".equals(money)) {
                money = "1399";
            } else if ("6".equals(money)) {
                money = "4";
            } else if ("18".equals(money)) {
                money = "12";
            } else if ("50".equals(money)) {
                money = "35";
            }

            this.saveError(certificateCode,money,rebate,"110",type,uid,"params为空");

            if (StringUtils.isNotEmpty(certificateCode)) {
                String r = sendHttpsCoon(url, certificateCode);
                JSONObject params = JSONObject.parseObject(r);
                System.out.println("*****************" + params);
                String code = "";
                String environment = "";
                String transaction_id = "";
                final String orderNum = DateUtil.getRechargeOrderNum();//根据当前时间生成订单号，yyMMddHHmmssSSS + 0~1000000随机数
                if (params != null) {

                    code = String.valueOf(params.get("status"));
                    this.saveError(certificateCode,money,rebate,code,type,uid,params.toString());

                    if ("0".equals(code)) {//成功
                        environment = String.valueOf(params.get("environment"));
                        String r_receipt = params.getString("receipt");
                        JSONObject returnJson = JSONObject.parseObject(r_receipt);
                        System.out.println("*****************" + returnJson);
                        //String in_app = returnJson.getString("in_app");
                        JSONArray jsonArray = (JSONArray) returnJson.get("in_app");// 订单列表
                        JSONObject targetOrder = null;
                        String product_id = null;
                        for (int i = 0; i < jsonArray.size(); i++) {

                            targetOrder = jsonArray.getJSONObject(i);//获取订单信息对象
                            product_id = targetOrder.getString("product_id");//获取产品信息
                            transaction_id = targetOrder.getString("transaction_id");// transaction_id交易号

                            if(product_id.equals("com.BeijingICanIShowEducation.fourc")){
                                money = "4";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.fourb")){
                                money = "12";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.thirty")){
                                money = "30";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.fouara")){
                                money = "35";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.SixtyTwo")){
                                money = "62";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.SixtyTwThree")){
                                money = "132";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.Twohundredandninetyeight")){
                                money = "298";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.SixtyTw")){
                                money = "412";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.SixHundredAndNinetyNine")){
                                money = "699";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.Ninehundredandninetyeight")){
                                money = "998";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.OneThousandoneHundred")){
                                money = "1189";
                            }else if(product_id.equals("com.BeijingICanIShowEducation.OneThousandThreeHundred")){
                                money = "1399";
                            }

                            this.saveError(certificateCode,money,rebate,"111",type,uid,"params再次为空");

                            if (!ISsoLoginHelper.confirmPay(uid, transaction_id)) {//验证订单是否已经充值
                                //保存充值记录
                                ISsoLoginHelper.savePay(uid, transaction_id, money);
                                //进行充值
                                saveRecharge(rebate, orderNum, uid, money, environment, transaction_id,type);
                            }
                        }

                        return R.ok();
                    } else {//失败

                        final String url1 = url;
                        final String certificateCode1 = certificateCode;
                        final String environment1 = environment;
                        final String transaction_id1 = transaction_id;
                        final String money1 = money;//充值金额
                        final Timer timer = new Timer();
                        timer.schedule(new TimerTask() {

                            @Override
                            public void run() {
                                if (map.get(certificateCode1) != null) {
                                    map.put(certificateCode1, map.get(certificateCode1) + 1);
                                } else {
                                    map.put(certificateCode1, 1);
                                }
                                if (map.get(certificateCode1) >= 60) {
                                    map.remove(certificateCode1);
                                    timer.cancel();
                                }
                                String r1 = sendHttpsCoon(url1, certificateCode1);
                                if (JSONObject.parseObject(r1).getString("status").equals("0")) {
                                    if (!ISsoLoginHelper.confirmPay(uid, transaction_id1)) {//验证订单是否已经充值
                                        //保存充值记录
                                        ISsoLoginHelper.savePay(uid, transaction_id1, money1);
                                        //进行充值
                                        saveRecharge(rebate, orderNum, uid, money1, environment1, transaction_id1,type);
                                    }
                                    map.remove(certificateCode1);
                                    timer.cancel();
                                }
                                //System.out.println("设定指定任务task在指定延迟delay后执行");
                            }
                        }, 1000, 10000);

                        return R.error("68");
                    }
                } else {

                    this.saveError(certificateCode,money,rebate,"111",type,uid,"params再次为空");
                    return R.error();
                }

            } else {
                return R.error();
            }
        }


        /**
         * 接收iOS端发过来的购买凭证
         * @param
         */
        @RequestMapping("/validateAgain")
        @ResponseBody
        public R validateAgain(HttpServletRequest req){

            Integer uid = ISsoLoginHelper.confirm(req);
            Map map1 = new HashMap();
            map1.put("uid",uid);
            List<WfIospayErrorEntity> entityList =  iospayErrorService.queryList(map1);
            for(int i=0; i<entityList.size();i++) {
                WfIospayErrorEntity error = entityList.get(i);
                String certificateCode = error.getCertificatecode();
                String money = error.getMoney();//充值金额
                String rebate = error.getRebate();//赠送金额
                String type = error.getType();//1、正式  2、测试
                String url = null;
                url = type.equals("1") ? certificateUrl : certificateUrlTest;
                //url = certificateUrl;  //正式

                if (StringUtils.isNotEmpty(certificateCode)) {
                    String r = sendHttpsCoon(url, certificateCode);
                    JSONObject params = JSONObject.parseObject(r);
                    System.out.println("*****************" + params);
                    String code = "";
                    String environment = "";
                    String transaction_id = "";
                    final String orderNum = DateUtil.getRechargeOrderNum();//根据当前时间生成订单号，yyMMddHHmmssSSS + 0~1000000随机数
                    if (params != null) {
                        code = String.valueOf(params.get("status"));
                        if ("0".equals(code)) {//成功
                            environment = String.valueOf(params.get("environment"));
                            String r_receipt = params.getString("receipt");
                            JSONObject returnJson = JSONObject.parseObject(r_receipt);
                            System.out.println("*****************" + returnJson);
                            String in_app = returnJson.getString("in_app");

                            if (in_app.endsWith("]")) {
                                JSONObject in_appJson = JSONObject.parseObject(in_app.substring(1, in_app.length() - 1));
                                transaction_id = in_appJson.getString("transaction_id");   // 订单号
                            }
                            error.setResultcode("0");
                            iospayErrorService.update(error);//再次验证成功后，将resultcode改为0
                            //保存充值记录
                            saveRecharge(rebate, orderNum, uid, money, environment, transaction_id,type);
                            return R.ok();
                        } else {//失败

                            return R.error("68");//支付验证失败
                        }
                    } else {
                        return R.error("68");
                    }
                }
            }
            return R.error("68");
        }


    /**
     * 接收iOS端发过来的购买凭证
     * @param
     */
    @RequestMapping("/validate")
    @ResponseBody
    public R validate(HttpServletRequest req){

        Integer uid = ISsoLoginHelper.confirm(req);
        Map map1 = new HashMap();
        map1.put("uid",uid);
        String certificateCode = req.getParameter("certificateCode");
        String money = req.getParameter("money");//充值金额
        String rebate = "0";//赠送金额
        String type = "1";//1、正式  2、测试
        String url = null;
        url = type.equals("1") ? certificateUrl : certificateUrlTest;
        //url = certificateUrl;  //正式

        if (StringUtils.isNotEmpty(certificateCode)) {
            String r = sendHttpsCoon(url, certificateCode);
            JSONObject params = JSONObject.parseObject(r);
            System.out.println("*****************" + params);
            String code = "";
            String environment = "";
            String transaction_id = "";
            final String orderNum = DateUtil.getRechargeOrderNum();//根据当前时间生成订单号，yyMMddHHmmssSSS + 0~1000000随机数
            if (params != null) {
                code = String.valueOf(params.get("status"));
                if ("0".equals(code)) {//成功
                    environment = String.valueOf(params.get("environment"));
                    String r_receipt = params.getString("receipt");
                    JSONObject returnJson = JSONObject.parseObject(r_receipt);
                    System.out.println("*****************" + returnJson);
                    String in_app = returnJson.getString("in_app");

                    if (in_app.endsWith("]")) {
                        JSONObject in_appJson = JSONObject.parseObject(in_app.substring(1, in_app.length() - 1));
                        transaction_id = in_appJson.getString("transaction_id");   // 订单号
                    }
                    //保存充值记录
                    saveRecharge(rebate, orderNum, uid, money, environment, transaction_id,type);
                    return R.ok();
                } else {//失败

                    return R.error("68");//支付验证失败
                }
            } else {
                return R.error("68");
            }
        }
        return R.error("68");
    }

    }